import React, { Component } from 'react';
import QueryList from '@/components/basicWidget/QueryList';
import { TableButton } from '@/components/basicWidget/Button';
import { Modal, message } from 'antd';
import { getContext } from '@/context/common/applicationContext';
import FormWidget from '@/components/basicWidget/FormWidget';
import { deleteDocumentsByCondition, updateDocumentById } from '@/service/document/documentService';
import './index.css'
import moment from 'moment';

/**
 * 将用户信息映射到组件属性
 * @param {Object} state - 全局状态对象
 * @returns {Object} - 包含用户信息的对象
 */
const mapToProps = (state) => {
    return {
        user: state.user
    }
}

/**
 * 待办事项管理组件
 * @author liu_jshan
 * @since 20241130
 */
class todoManage extends Component {
    /**
     * 构造函数
     * @param {Object} props - 组件属性
     */
    constructor(props) {
        super(props)
        this.state = {
            isModalVisible: false,
            readOnlyPage: false,
            modalTitle: '添加代办',
            editId: null
        }
    }

    /**
     * 组件挂载后执行的操作
     */
    async componentDidMount() {
    }

    /**
     * 为表格添加操作列和数据
     * @param {Array} columns - 原始列数据
     * @param {Array} data - 原始数据
     * @returns {Object} - 包含新列和新数据的对象
     */
    actionColumns = (columns, data) => {
        columns.push({ title: '详情', dataIndex: 'operate' })
        data = data.map(item => {
            item.operate = (
                <div className='todo-manege-operate'>
                    <TableButton onClick={() => {
                        this.setState({
                            isModalVisible: true,
                            readOnlyPage: item.todoState !== 'finish' ? false : true,
                            modalTitle: item.todoState !== 'finish' ? '待办编辑' : '待办查看',
                            editId: item.id
                        })
                    }}>{item.todoState !== 'finish' ? '编辑' : '查看'}</TableButton>
                    {
                        item.todoState !== 'finish' ?
                            <TableButton onClick={async () => {
                                const response = await updateDocumentById({
                                    serviceName: 'blog',
                                    collectionName: 'customer_todo_info',
                                    id: item.id,
                                    content: {
                                        todoState: 'finish',
                                        realFinishDate: moment().format('YYYY-MM-DD')
                                    }
                                })
                                if (response && response.code === 200) {
                                    message.success('操作成功')
                                    await this.queryList.onQuery()
                                } else {
                                    message.warning('操作失败，请联系管理员')
                                }
                            }}>完成</TableButton> : ''
                    }
                </div>
            )
            return item
        })
        return { newColumns: columns, newData: data }
    }

    /**
     * 打开添加待办事项模态框
     */
    onAdd = () => {
        this.setState({
            isModalVisible: true,
            readOnlyPage: false,
            modalTitle: '添加代办',
            editId: null
        });
    }

    /**
     * 删除选中的待办事项
     */
    onRemove = async () => {
        const selectedRowKeys = this.queryList.state.selectedRowKeys
        if (!selectedRowKeys || selectedRowKeys.length === 0) {
            message.warning('请选择要删除的数据')
            return false
        }
        const response = await deleteDocumentsByCondition({
            serviceName: 'blog',
            collectionName: 'customer_todo_info',
            searchFactory: [
                {
                    fieldName: 'id',
                    fieldValue: selectedRowKeys,
                    operate: 'in'
                }
            ]
        })
        if (response && response.code === 200) {
            message.success('删除成功')
            await this.queryList.onQuery()
        }
    }

    /**
     * 关闭模态框
     */
    handleCancel = () => {
        this.setState({ isModalVisible: false });
    }

    /**
     * 渲染组件
     * @returns {JSX.Element} - 组件的JSX结构
     */
    render() {
        return (
            <>
                <QueryList
                    queryCode='todoManage'
                    actionColumns={this.actionColumns}
                    onAdd={this.onAdd}
                    onRemove={this.onRemove}
                    refData={{
                        custId: this.props.user.id
                    }}
                    ref={queryList => this.queryList = queryList}
                >
                </QueryList>
                <Modal
                    title={this.state.modalTitle}
                    open={this.state.isModalVisible}
                    onCancel={this.handleCancel}
                    width='60%'
                    footer={null}
                    destroyOnClose={true}
                >
                    <FormWidget
                        code='todoBasicInfo'
                        id={this.state.editId}
                        serviceName='blog'
                        collectionName='customer_todo_info'
                        initFormData={{
                            customerId: this.props.user.id,
                            todoState: 'unFinish'
                        }}
                        readOnlyPage={this.state.readOnlyPage}
                        onDataCreate={async (childState, type) => {
                            this.queryList.onQuery()
                            this.handleCancel()
                        }}
                    >
                    </FormWidget>
                </Modal>
            </>
        )
    }
}

export default getContext(todoManage, mapToProps);